/**
 * 面试题：求x的n次方
 */
const X = 1
const N = 100

function fun1(x: number, n: number) {
    const start = new Date().getTime()
    let count = 1
    for (let i = 0; i < n; i++) {
        count *= x
    }
    const end = new Date().getTime()
    console.log(`fun1 ${x}^${n} = ${count}，耗时：${end-start}ms`) // 0ms
}
fun1(X, N)

let count = 1
let start = new Date().getTime()
function fun2(x: number, n: number): number {
    if (n === 0) {
        return 1
    }
    return fun2(x, n-1) * x
}
count = fun2(X, N)
let end = new Date().getTime()
console.log(`fun2 2^10 = ${count}，耗时：${end-start}ms`) // 0ms

start = new Date().getTime()
function fun3(p: number, q: number): number {
    const x: number = parseInt(p + '')
    const n: number = parseInt(q + '')
    if (n <= 0) {
        return 1
    }
    if (n % 2 === 1) {
        return fun3(x, n/2) * fun3(x, n/2) * x
    }
    return fun3(x, n/2) * fun3(x, n/2)
}
count = fun3(X, N)
end = new Date().getTime()
console.log(`fun3 2^10 = ${count}，耗时：${end-start}ms`) // 2ms

start = new Date().getTime()
function fun4(x: number, n: number): number {
    if (n <= 0) {
        return 1
    }
    const p = parseInt(x + '')
    const q = parseInt(n + '')
    const temp = fun4(p, q/2)
    if (q % 2 === 1) {
        return temp * temp * p
    }
    return temp * temp
}
count = fun4(X, N)
end = new Date().getTime()
console.log(`fun4 2^10 = ${count}，耗时：${end-start}ms`) // 2ms